/*
 * Main.cpp
 *
 *  Created on: Jan 8, 2011
 *      Author: Kevin Mueller
 */

#include "Main.h"

#include "Clock.h"
#include "PositioningSystem.h"
#include "Settings.h"
#include "SearchService.h"
#include "RoutingService.h"
#include "QtFile.h"

#include "../core/Opennav.h"

#include <QtCore>

using namespace opennav;

Main* Main::instance = 0;

Main& Main::getInstance() {
	if (instance == 0) {
		instance = new Main();
		instance->construct();
	}
	return *instance;
}

Main::Main() {
	searchService = NULL;
	routingService = NULL;
	routeSettings = NULL;
	map = NULL;
	position = NULL;
	settings = NULL;
	clock = NULL;
}

void Main::construct() {
	clock = new Clock(0);
	position = new PositioningSystem(0);
	settings = new Settings(0);
}

Main::~Main() {
	delete searchService;
	delete routeSettings;
	delete routingService;
	delete map;
	delete position;
	delete settings;
	delete clock;
}

void Main::destruct() {
	delete this;
	instance = 0;
}

bool Main::init(int argc, char** argv) {
	QtFile* mapFp = new QtFile(settings->getMapFileLocation()->get());
	if (!mapFp->exists()) {
		QString msg = QString("Map file doesn't exists. Please move a valid %1 map file to %2");
		msg = msg.arg(Main::APPLICATION_NAME());
		msg = msg.arg(settings->getMapFileLocation()->get());
		qCritical() << msg;
		delete mapFp;
		return false;
	}
	if (!mapFp->readable()) {
		QString msg = QString("Map file isn't readable by user. Please check permissions on %1");
		msg = msg.arg(settings->getMapFileLocation()->get());
		qCritical() << msg;
		delete mapFp;
		return false;
	}

	map = new Map(mapFp, true);
	searchService = new SearchService(map);
	routeSettings = new RouteSettings(0);
	routingService = new RoutingService(map);

	position->init();

	return true;
}

Clock& Main::getClock() const {
	return *clock;
}

PositioningSystem& Main::getPositioningSystem() const {
	return *position;
}

Settings& Main::getSettings() const {
	return *settings;
}

Map& Main::getMap() const {
	return *map;
}

RouteSettings* Main::getRouteSettings() const {
	return routeSettings;
}

SearchService& Main::getSearchService() const {
	return *searchService;
}

RoutingService& Main::getRoutingService() const {
	return *routingService;
}

void Main::normalMode() {
//	qDebug() << this << " enter normal mode";
	getPositioningSystem().normalMode();
}

void Main::powerSave() {
//	qDebug() << this << " enter power save mode";
	getPositioningSystem().powerSave();
}

bool Main::isMoving() {
	QGeoPositionInfo info = getPositioningSystem().getLastPosition();
	return (info.isValid() && info.attribute(QGeoPositionInfo::GroundSpeed)
			> 2.0);
}

bool Main::isNavigating() {
	return false;
}

//#define SIMPLE_BRIGHTNESS_GCONF_PATH "/system/osso/dsm/display"
//#define BRIGHTNESS_KEY SIMPLE_BRIGHTNESS_GCONF_PATH "/display_brightness"
